import React, { Component, useMemo } from 'react'
import { View, Text } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { timestampToTime, transformData } from '@/utils'
import { SpNavBar } from '@/components'
import api from '@/api'
import './editLocation.scss'
import UploadUtil from '@/utils/UploadUtil'
import { connect } from 'react-redux'
import ShopCheck from '../../my/address/add/comps/shopCheck'
import {
    Form,
    Input,
    Button,
    Cascader,
    TextArea,
    Space,
    Dialog,
    Switch,
    Picker,
    Selector,
    Popup
} from 'antd-mobile'
import cart from '@/store/slices/cart'
const basicColumns = [
    [
        { label: '00时', value: '00' },
        { label: '01时', value: '01' },
        { label: '02时', value: '02' },
        { label: '03时', value: '03' },
        { label: '04时', value: '04' },
        { label: '05时', value: '05' },
        { label: '06时', value: '06' },
        { label: '07时', value: '07' },
        { label: '08时', value: '08' },
        { label: '09时', value: '09' },
        { label: '10时', value: '10' },
        { label: '11时', value: '11' },
        { label: '12时', value: '12' },
        { label: '13时', value: '13' },
        { label: '14时', value: '14' },
        { label: '15时', value: '15' },
        { label: '16时', value: '16' },
        { label: '17时', value: '17' },
        { label: '18时', value: '18' },
        { label: '19时', value: '19' },
        { label: '20时', value: '20' },
        { label: '21时', value: '21' },
        { label: '22时', value: '22' },
        { label: '23时', value: '23' },

    ],
    [
        { label: '00分', value: '00' },
        { label: '30分', value: '30' },
    ],
]
import {
    SHOP_MAP,
    SELECCAT_MAP,
    BRAND_MAP2,
    GOOD_MAP
} from '../../good/const'
class EditLocation extends Component {
    formRef = React.createRef()
    constructor(props) {
        super(props);
        this.state = {
            items: [],
            regions: [],
            regions_id: [],
            placeSearch: '',
            visible: false,
            shopList: [],
            shopItem: [],
            paramsId: '',
            mearchInfo: {}
        }
    }
    componentDidMount() {
        this.getAdressItem()
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()
        this.getShopDetail(id)
        this.setState({ paramsId: id })

    }
    async getAdressItem() {
        const data = await api.address.areaList()
        this.setState({
            items: data
        })

    }
    searchLoction = () => {
        // //关键字查询
        const values = this.formRef.current?.getFieldsValue()
        console.log('000000', values)
        if (values.regions_id.length == 0) {
            this.$message.error('请选择地区')
            return
        }
        if (!values.address) {
            this.$message.error('请输入具体位置')
            return
        }
        this.state.placeSearch.setCity(this.state.regions[2])
        this.state.placeSearch.search(values.address, function (status, result) {

        });
    }
    async getShopDetail(id) {
        const form = await api.shop.getMerchantById({ 'distributor_id': id })
        this.setState({
            shopItem: form.offline_aftersales_distributor_id ? form.offline_aftersales_distributor_id : [],
            mearchInfo: form
        })
        if (form.offline_aftersales_address.hours) {
            let hour = form.offline_aftersales_address.hours?.split('-')
            form.offline_aftersales_address.startTime = hour[0].split(':')
            if (form.offline_aftersales_address.startTime.length >= 2 && form.offline_aftersales_address.startTime[0].length > 0 && form.offline_aftersales_address.startTime[1].length > 0) {
            } else {
                form.offline_aftersales_address.startTime = []
            }
            form.offline_aftersales_address.endTime = hour[1].split(':')
            if (form.offline_aftersales_address.endTime.length >= 2 && form.offline_aftersales_address.endTime[0].length > 0 && form.offline_aftersales_address.endTime[1].length > 0) {

            } else {
                form.offline_aftersales_address.endTime = []
            }
        }

        form.offline_aftersales_address.offline_aftersales = form.offline_aftersales
        form.offline_aftersales_address.offline_aftersales_other = form.offline_aftersales_other
        this.formRef.current?.setFieldsValue(form.offline_aftersales_address)

        const params = {
            page: 1,
            pageSize: 1000,
            distributor_id: id
        }
        const { list, total_count } = await api.shop.getMerchantAftersales(params)
        let arr = list.filter((item) => {
            // return item.distributor_id == val[0]
            return this.state.shopItem.includes(item.distributor_id)
        })
        let list2 = this.getGood(arr)
        this.setState({
            shopList: list2,
        })
        this.formRef.current?.setFieldsValue({ distributor_id: this.state.shopItem })

    }

    getRegionNameById(region, district) {
        let result = []
        function getRegionName(_district, index) {
            const res = _district.find((item) => item.value == region[index])
            if (res) {
                result.push(res.label)
                if (res.children) {
                    getRegionName(res.children, ++index)
                }
            }
        }
        if (Array.isArray(region) && region.length > 0) {
            getRegionName(district, 0)
        }
        return result
    }
    onFinish = (values) => {
        console.log(values)
        if (values.quantity) {

        }
        this.onSubmit(values)
    }
    onSubmit = async () => {

        const values = this.formRef.current?.getFieldsValue()
        // Dialog.alert({
        //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        // })
        var params = {
            ...this.mearchInfo
        }
        values.startTime = values.startTime?.join(':')

        values.endTime = values.endTime?.join(':')
        values.hours = values.startTime + '-' + values.endTime
        values.regions = this.state.regions
        values.area = this.state.regions[2]
        values.province = this.state.regions[0]
        values.city = this.state.regions[1]
        params.offline_aftersales_address = values



        params.offline_aftersales = Boolean(values.offline_aftersales)
        params.offline_aftersales_other = Boolean(values.offline_aftersales_other)
        params.offline_aftersales_distributor_id = this.state.shopItem

        console.log(params)
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()

        params.distributor_id = id
        await api.shop.editMerchant(params)

        Taro.navigateBack()
    }
    onClickGoogs = async (values) => {
        console.log('index-294打印values', values)
        let list = this.getGood(values)
        let lll = list.map((value) => {
            return value.value
        })
        this.setState({
            shopList: list,
            shopItem: lll
        })
        this.formRef.current?.setFieldsValue({ distributor_id: lll })
    }
    getGood(value) {
        let list = this.transformData(value, SHOP_MAP)
        return list
    }
    transformData(data, obj) {
        let list = []
        data.forEach((item) => {
            let currentItem = {}
            for (let key in obj) {
                currentItem[obj[key]] = item[key]
            }
            if (item.children) {
                currentItem.children = transformData(item.children, obj)
            }
            list.push(currentItem)
        })
        return list
    }
    state = {}
    render() {
        return (
            <View >
                <SpNavBar title='到店退货'></SpNavBar>
                <View className='edit-location'>
                    <Form ref={this.formRef}
                        layout='horizontal'
                        footer={
                            <Button block type='submit' color='primary' size='large' >
                                提交
                            </Button>
                        }
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                        initialValues={{}}>
                        <Form.Item
                            name='offline_aftersales'
                            label='本店订单'
                            valuePropName='checked'
                            help='启用后本店订单买家发起退货退款申请时可选择到店退货，关闭时本店订单仅可使用快递退货；商家发起的售后订单不受此规则限制。'
                        >
                            <Switch />
                        </Form.Item>
                        <Form.Item
                            name='offline_aftersales_other'
                            label='其他店铺'
                            valuePropName='checked'
                            help='启用后其他店铺在设置可退货店铺时可选择本店（即本店可接收其他店铺订单店退货）；商家发起的售后订单不受此规则限制。'
                        >
                            <Switch />
                        </Form.Item>
                        <Form.Header>
                            本店退货点：退货点信息会在买家选择到店退货时展示，初次使用此功能时本店退货点默认为选中状态（可退货店铺列表内未展示），可在保存店铺信息后再次进入此页面移除。
                        </Form.Header>
                        <Form.Item label='退货点名称' name='name'

                        >
                            <Input value='' placeholder='请填写退货点名称' />
                        </Form.Item>
                        <Form.Item label="退货点地址" name='regions_id'
                            trigger='onConfirm'

                            onClick={(e, datePickerRef) => {
                                datePickerRef.current?.open() // ⬅️
                            }}
                        >
                            <Cascader
                                options={this.state.items}
                                value={this.state.regions_id}
                                onChange
                            >
                                {items => {
                                    if (items.every(item => item === null)) {
                                        return '未选择'
                                    } else {
                                        this.state.regions = items.map(item => item?.label ?? '未选择')
                                        return items.map(item => item?.label ?? '未选择').join('-')
                                    }
                                }}
                            </Cascader>
                        </Form.Item>
                        <Form.Item name='address' label='详细地址'>
                            <TextArea
                                placeholder='请填写详细地址'
                                maxLength={100}
                                showCount
                            />
                        </Form.Item>
                        <Form.Item label='联系电话' name='mobile'

                        >
                            <Input placeholder='请填写准确的联系电话' />
                        </Form.Item>
                        <Form.Item label="经营开始时间" name='startTime'
                            trigger='onConfirm'

                            onClick={(e, datePickerRef) => {
                                datePickerRef.current?.open() // ⬅️
                            }}
                        >
                            <Picker
                                columns={basicColumns}
                            >
                                {value => value.length > 0 ? value[0].value + ':' + value[1].value : '请选择开始时间'}
                            </Picker>
                        </Form.Item>
                        <Form.Item label="经营结束时间" name='endTime'
                            trigger='onConfirm'

                            onClick={(e, datePickerRef) => {
                                datePickerRef.current?.open() // ⬅️
                            }}
                        >
                            <Picker
                                columns={basicColumns}
                            >
                                {value => value.length > 0 ? value[0].value + ':' + value[1].value : '请选择结束时间'}
                            </Picker>
                        </Form.Item>
                        <Form.Item label="选择店铺" name='distributor_id'
                            trigger='onConfirm'
                            onClick={(e) => {
                                this.setState({
                                    visible: true
                                })
                            }}
                        >
                            {/* <Input readOnly /> */}
                            <Selector
                                columns={2}
                                multiple
                                disabled
                                options={this.state.shopList}
                            />
                        </Form.Item>

                    </Form>

                </View>
                <Popup
                    position='right'
                    showCloseButton
                    visible={this.state.visible}
                    onMaskClick={() => {
                        this.setState({
                            visible: false
                        })
                    }}
                    destroyOnClose
                    onClose={() => {
                        this.setState({
                            visible: false,
                        })
                    }}
                >
                    <div className='rigth-btn' onClick={() => {
                        this.setState({
                            visible: false,
                        })
                    }}>
                        确定
                    </div>
                    <div className='popup-body'>
                        <div >
                            <ShopCheck shoptype={2} distributor_id={this.state.paramsId} onChange={this.onClickGoogs} selected={this.state.shopItem} value='1'></ShopCheck>
                        </div>
                    </div>
                </Popup>

            </View >
        );
    }
}

export default EditLocation;